package org.zju.demo.service.impl;

import org.zju.demo.model.Category;
import org.zju.demo.service.intf.CategoryInfoIntf;
import org.zju.demo.utils.Constant;
import org.zju.demo.utils.HibernateUtil;

import java.util.List;

/**
 * Created by admin on 2015/8/27.
 */
public class CategoryInfoImpl implements CategoryInfoIntf{
    public Category findByCategoryName(String categoryName) {
        String hql = "from Category where categoryName=?";
        String parameter[] = {categoryName};
        return (Category) HibernateUtil.objectQuery(hql, parameter);
    }

    public int addCategory(String categoryName) {
        Category category = findByCategoryName(categoryName);
        if (category != null) {
            return Constant.ALREADY_EXISTS;
        }

        category = new Category();
        category.setCategoryName(categoryName);
        return HibernateUtil.saveIfNotExists(category);
    }

    public List<Category> getAllCategory() {
        String hql = "from Category";
        List<Category> list = HibernateUtil.executeQuery(hql, null);
        return list;
    }

    public Category findById(int id) {
        String hql = "from Category where categoryId=?";
        String [] parameters = {Integer.toString(id)};
        return (Category)HibernateUtil.objectQuery(hql, parameters);
    }
}
